import os, zipfile
import shutil
from jinja2 import Environment, FileSystemLoader, PackageLoader
from app.config.secure import REPORT_DIR, PPYY_DIR
from app.libs.paperyy import ExportPaperYY
from bs4 import BeautifulSoup


class ExportReport():
    def __init__(self, report, order_num):
        self.report_dir = REPORT_DIR + 'samereport_' + order_num
        self.ppyy = report
        self.ppyy_model = ExportPaperYY(report)
        self.ppyy_model.export()
        self.ppyy_details = self.ppyy_model.LeBlanc()
        self.ppyy_origins = self.ppyy_model.Galio()
        self.details = []
        self.ppyy_model.export()
        self.SENTENCE_ENVIRONMENT = Environment(
            loader=PackageLoader('app.ExportReport', 'report_templates'),
            trim_blocks=False)
        if not self.is_exists_report():
            os.mkdir(self.report_dir)

    def ppyy_info(self):
        infos = self.ppyy_model.LeBlanc()
        return infos

    def sentence_render_template(self, template_filename, contexts):
        return self.SENTENCE_ENVIRONMENT.get_template(template_filename).render(contexts=contexts)

    @classmethod
    def get_MD5(cls, file_path):
        files_md5 = os.popen('md5 %s' % file_path).read().strip()
        file_md5 = files_md5.replace('MD5 (%s) = ' % file_path, '')
        return file_md5

    def create_report_directory(self, path='', out=''):
        if path == '':
            path = 'app/ExportReport/report_templates/samereport'
        if out == '':
            out = self.report_dir
        for files in os.listdir(path):
            name = os.path.join(path, files)
            back_name = os.path.join(out, files)
            if os.path.isfile(name):
                if os.path.isfile(back_name):
                    if self.get_MD5(name) != self.get_MD5(back_name):
                        shutil.copy(name, back_name)
                else:
                    shutil.copy(name, back_name)
            else:
                if not os.path.isdir(back_name):
                    os.makedirs(back_name)
                self.create_report_directory(name, back_name)

    def create_index_html(self, index, contexts):
        fname = self.report_dir + "/htmls/sentence_detail/detail_" + index + ".html"
        # originSentence = contexts['originSentence'].replace('<em class="similar">', '').replace('</em>', '')
        # str_words_list = jieba.lcut(originSentence)
        # str_words = []
        # similarWords = []
        # for words in str_words_list:
        #     if len(words) >= 2:
        #         str_words.append(words)
        # for i in str_words:
        #     res = synonyms.nearby(i)[0]
        #     print(res)
        #     if len(res) > 1:
        #         similarWords.append(res)
        with open(fname, 'w') as f:
            html = self.SENTENCE_ENVIRONMENT.get_template('detail.html').render(contexts=contexts)
            f.write(html)

    def create_paper_html(self):
        fname = self.report_dir + "/htmls/detail_report/paper.html"
        self.paragraphs = []
        count = 0
        for index, origin in enumerate(self.ppyy_origins):
            section = origin['sectionContent']
            for detail in self.ppyy_details[index]['sectionSourcesDetail']:
                sentenceDetailStruct = {
                    'index': count,
                    'info': detail
                }
                self.details.append(sentenceDetailStruct)
                section = section.replace(detail['originSentence'],
                                          f'<a target="right" href="../sentence_detail/detail_{count}.html" style="color:green">' +
                                          detail[
                                              'originSentence'] + '</a>')
                count += 1
            bs = BeautifulSoup(section, "html.parser")
            ps = bs.find_all('p')
            for p in ps:
                self.paragraphs.append(p)
        with open(fname, 'w') as f:
            html = self.sentence_render_template('paper.html', contexts=self.paragraphs)
            f.write(html)

    def create_pdf_html(self, view_info):
        fname = self.report_dir + "/htmls/pdf.html"
        with open(fname, 'w') as f:
            html = self.SENTENCE_ENVIRONMENT.get_template('pdf.html').render(contexts=self.paragraphs,
                                                                             view_info=view_info)
            f.write(html)
        if os.path.exists(self.report_dir + "/htmls/pdf.html"):
            os.system('wkhtmltopdf ' + self.report_dir + "/htmls/pdf.html " + self.report_dir + "/简明打印版.pdf")

    def create_report_html(self, contexts):
        fname = self.report_dir + "/检测报告详细版.html"
        with open(fname, 'w') as f:
            html = self.sentence_render_template('检测报告详细版.html', contexts=contexts)
            f.write(html)

    def create_orginal_html(self, contexts):
        fname = self.report_dir + "/htmls/view_original_.html"
        with open(fname, 'w') as f:
            html = self.sentence_render_template('view_original_.html', contexts=contexts)
            f.write(html)

    def zip_report(self):
        zipf = zipfile.ZipFile(self.report_dir + '.zip', 'w')
        pre_len = len(os.path.dirname(self.report_dir))
        for parent, dirnames, filenames in os.walk(self.report_dir):
            for filename in filenames:
                pathfile = os.path.join(parent, filename)
                arcname = pathfile[pre_len:].strip(os.path.sep)  # 相对路径
                zipf.write(pathfile, arcname)
        zipf.close()
        shutil.rmtree(self.report_dir)

    def is_exists_report(self):
        if os.path.exists(self.report_dir + '.zip'):
            return True
        else:
            return False


if __name__ == '__main__':
    s = ExportReport('123')
    s.create_report_directory()
